package com.objectproject.main.service.subsystem;

import java.util.ArrayList;
import java.util.HashSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.objectproject.main.dao.MembershipDAOImpl;
import com.objectproject.main.dao.MyGroupHierarchyDAOImpl;
import com.objectproject.main.model.MyGroup;
import com.objectproject.main.model.MyUser;

@Service
public class MembershipResolver {
	
	@Autowired
	MembershipDAOImpl membershipDAOImpl;
	
	@Autowired
	MyGroupHierarchyDAOImpl myGroupHierarchyDAOImpl;
	
	
	
	public boolean isMemberOf(MyUser myUser, MyGroup myGroup){
		ArrayList<MyGroup> myGroups = retrieveFullGroupsOfEasy(myUser);
		if(myGroups.contains(myGroup))
			return true;
		return false;
	}
	
	public ArrayList<MyGroup> getGroupsOf(MyUser myUser){
		return retrieveFullGroupsOfEasy(myUser);
	}
	
	//dangerous to heap size at memory
	@Deprecated
	public ArrayList<Long> getAllMembersOf(MyGroup myGroup){
		ArrayList<Long> groupIds = myGroupHierarchyDAOImpl.selectDescendantGroupIds(myGroup.getGroupId());
		HashSet<Long> members = new HashSet<Long>(); 
		
		groupIds.add(myGroup.getGroupId());//현재 그룹포함
		
		for(Long currentLong:groupIds){
			members.addAll(membershipDAOImpl.selectMemberIds(currentLong));
		}
		
		return new ArrayList<Long>(members);
	}
	
	//helper
	private ArrayList<MyGroup> retrieveFullGroupsOfEasy(MyUser myUser){
		ArrayList<MyGroup> groups = membershipDAOImpl.selectGroups(myUser.getUserId());
		
		HashSet<MyGroup> fullGroups = new HashSet<MyGroup>(groups);
		
		for(MyGroup currentGroup:groups){
			fullGroups.addAll(myGroupHierarchyDAOImpl.selectAncestorGroups(currentGroup.getGroupId()));
		}
		
		return new ArrayList<MyGroup>(fullGroups);
	}
	
	
}
